<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Overtrue\Wechat\Server;
use Overtrue\Wechat\Message;
use Overtrue\Wechat\User as WxUser;
use Overtrue\Wechat\Messages\Image;
use Overtrue\Wechat\QRCode;
use App\User;

//https://github.com/overtrue/wechat/wiki/%E4%BA%8C%E7%BB%B4%E7%A0%81
class WxController extends Controller {
    public function h()
    {
        //$at = 'AnCnxH0fYBGj9Oq23BhRNhH-Fh_GZX1YvFSMEUVqjZbFkQVW1qdg-DaagWSeP-uddeGqhPqK_mb6_vjMGF1HXB8ZnhI0_U9THdyAzdFJRb-LS_SBRcNB2LwNu_dgMfSXDLKcAIAMUT';
        //$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token={$at}";

        //$data ='[{"keywords": {"type":"click","name":"今日歌曲","key":"V1001_TODAY_MUSIC"},"num":151,"area":18017.24},{"date":"2014-09-07","num":103,"area":11703.9},{"date":"2014-09-08","num":66,"area":7378.92},{"date":"2014-09-09","num":192,"area":22160.96},{"date":"2014-09-10","num":183,"area":22059.72},{"date":"2014-09-11","num":184,"area":21212.68},{"date":"2014-09-12","num":119,"area":13960.93},{"date":"2014-09-13","num":0,"area":0},{"date":"2014-09-14","num":43,"area":5056.19},{"date":"2014-09-15","num":121,"area":12867.43},{"date":"2014-09-16","num":93,"area":8755.81},{"date":"2014-09-17","num":80,"area":9035.69},{"date":"2014-09-18","num":158,"area":17613.12},{"date":"2014-09-19","num":112,"area":12180.37},{"date":"2014-09-20","num":74,"area":8614.02},{"date":"2014-09-21","num":95,"area":10305.27},{"date":"2014-09-22","num":258,"area":30695.9},{"date":"2014-09-23","num":155,"area":17457.88},{"date":"2014-09-24","num":148,"area":16792.02},{"date":"2014-09-25","num":167,"area":20203.15},{"date":"2014-09-26","num":174,"area":20055.03},{"date":"2014-09-27","num":138,"area":15927.18},{"date":"2014-09-28","num":175,"area":19372.63},{"date":"2014-09-29","num":277,"area":30226.38},{"date":"2014-09-30","num":311,"area":33082.01},{"date":"2014-10-01","num":88,"area":9456.33},{"date":"2014-10-02","num":92,"area":9384.07},{"date":"2014-10-03","num":70,"area":7780.39},{"date":"2014-10-04","num":71,"area":7620.61},{"date":"2014-10-05","num":44,"area":4672.24}]';
        //dump(json_decode($data,true));
       // $json = load(public_path('json/test.json'));
        //dump(json_decode($json,true));
        //$u= 'qrscene_123123';
        //$pid = str_replace('qrscene_','',$u);
        //dump($pid);
        //$user = User::where('openid','oaS6YxI2Ijy4zIggo8KOK0wlkpw4')->first();
        $user = urldecode('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx257cb27d73738902&redirect_uri=http%3A%2F%2Fvyetqx7v4d.proxy.qqbrowser.cc%2Flogin&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect');
        dump($user);



    }
    public function index(){
        $server = new Server(env('WX_APPID'), env('WX_TOKEN'));
        $server->on('event', 'subscribe',[$this,'guanzhu']);
        $server->on('event', 'unsubscribe',[$this, 'qxgz']);
        $server->on('message','image', [$this, 'tp']);
        return $server->serve();
    }
    public function  qxgz($event){
        $openid = $event->FromUserName;
        $user = User::where('openid',$openid)->first();
        if ($user) {
            $user->status = 0;
            $user->save();
        }


    }
    public function guanzhu($event){ //当粉红关注本公众号时的调用方法
        $g = new WxUser(env('WX_APPID'), env('WX_SECRET'));
        $getmsg =  $g->get($event -> FromUserName); //获取关注本公众号用户信息

//      if (count(User::where('openid',$event->FromUserName)->first()) == 0) {


        $user =  User::where('openid', $event->FromUserName)->first(); //如果在数据库里能找到一行，且关注状态为1
        if($user && $user->status==1){ //此用户处于正常关注状态
            return;
        }

        if($user && $user->status==0){//如果在数据库里能找到一行，且关注状态为0
           $user->status = 1;
            $user->save();//已经定位到新增的这一行上了。
        } else {
            //如果没有关注过，并是直接扫公众号时入，作为顶级代理
            $user = new User();
            $user->openid = $event -> FromUserName;
            $user->name =  $getmsg -> nickname;
            $user->subtime = time();

            if ($event->EventKey) { //如果没有关注过，但是是扫描场景二维码进入的时
                $pid = str_replace('qrscene_','',$event->EventKey);
                $row = User::where('uid',$pid)->first();
                $user->p1 = $pid;
                $user->p2 =  $row->p1;
                $user->p3 =  $row->p2;
            }
            $user->save();//已经定位到新增的这一行上了。
            $this->qr($user->uid);//创建场景场景二维码
        }

//        } else {
//             $this->zcgz($event); //再次关注时增加一个方法
//        }

        return Message::make('text')->content('欢迎关注wechat!' . $event->FromUserName);
    }

    public function mkd(){ //场景二维码创建一个目录
        $path = str_replace('\\','/',public_path());
        $pdate = date('/Y/md');
        if (!is_dir($path . $pdate)) {
            mkdir( $path . $pdate, 0777, true);
        }
        return $path . $pdate;
    }
    public function qr($uid){
        $qrcode = new QRCode(env('WX_APPID'), env('WX_SECRET'));
        $result = $qrcode->forever($uid);// 或者 $qrcode->forever("foo");
        $ticket = $result->ticket; // 或者 $result['ticket'],维码的ticket，可用来换取二维码图片
        $path = $this->mkd() . '/' . 'qr_'.$uid . '.jpg'; //场景二维码的保存路径
        $qrcode->download($ticket, $path);
        return;
    }

    public function tp($event) {
        $key = 'd8e752de839269dfa1b4b20307b7ae52';
        $secret = 'dRG3nMp9zr5geBcXnHqCuli-6J8UP9TY';
        $url = urlencode($event->PicUrl);
        $url = "http://apicn.faceplusplus.com/v2/detection/detect?api_key={$key}&api_secret={$secret}&url={$url}&attribute=glass,pose,gender,age,race,smiling";
        $url = json_decode(file_get_contents($url),true);

        $face = $url['face'];
        echo '共检测到'. count($face) . "人，分别是\n";
        $f = '';
        foreach($face as $k => $v) {
            $f .=  '年龄为' . $v['attribute']['age']['value'] . ',性别为：' . $v['attribute']['gender']['value'] . ',性别的准确度为：'  . $v['attribute']['gender']['confidence'] . "%\n";
        }

        return $f;
    }




}
